﻿using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class BuildVersion {

	[MenuItem("Build/BuildXcodeProject")]
	static public void BuildXcodeProj() {
		BuildXcodeProjInternal ();
	}

	static public void BuildXcodeProjWithVersion() {
		string version = GetVersion ();
		if (version == string.Empty) {
			Debug.LogError ("cmd has no version param!");
			return;
		}
		PlayerSettings.bundleVersion = version;

		BuildXcodeProjInternal ();
	}

	static private string[] GetEditorBuildSettingScenes() {
		List<string> sceneList = new List<string> ();
		foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes) {
			sceneList.Add (scene.path);
		}

		if (sceneList.Count == 0) {
			return null;
		}

		return sceneList.ToArray ();
	}

	static private string GetVersion() {
		foreach (string arg in System.Environment.GetCommandLineArgs()) {
			string[] strs = arg.Split('=');
			if(strs.Length == 2 && strs[0] == "version") {
				return strs[1];
			}
		}

		return string.Empty;
	}

	static private void BuildXcodeProjInternal() {
		string[] scenes = GetEditorBuildSettingScenes ();
		if (scenes == null) {
			Debug.LogError ("Editor has no scene!");
			return;
		}

		BuildPipeline.BuildPlayer (scenes, "../ci/ngamexcode", BuildTarget.iOS, BuildOptions.AcceptExternalModificationsToPlayer);
	}

	[PostProcessBuild(100)]
	static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject) {
		Debug.Log ("BuildTarget " + target);
		Debug.Log ("Build Path " + pathToBuiltProject);
	}
}
